<template>
    <div>
        <el-select v-model="productVo.brand" placeholder="请选择品牌">
            <el-option
                    v-for="brand  in brandList"
                    :key="brand"
                    :label="brand"
                    :value="brand">
            </el-option>
        </el-select>
        <el-select v-model="productVo.productName" placeholder="请选择商品名">
            <el-option
                    v-for="productName in productNameList"
                    :key="productName"
                    :label="productName"
                    :value="productName">
            </el-option>
        </el-select>
        <el-button @click="fetchProducts">查询</el-button>
        <el-button @click="reset">重置</el-button>
        <!-- 商品数据表格 -->
        <el-table :data="productList" style="width: 100%">
            <el-table-column prop="variantId" label="商品ID" width="100"></el-table-column>
            <el-table-column prop="brand" label="品牌名称"></el-table-column>
            <el-table-column prop="productName" label="商品名称"></el-table-column>
            <el-table-column prop="typeName" label="包装类型名称"></el-table-column>
            <el-table-column prop="weight" label="单位重量"></el-table-column>
            <!-- 添加按钮列 -->
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button size="small" type="primary" @click="addRowToSelected(row)">添加</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页控件 -->
        <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page.currentPage"
                :page-size="page.pageSize"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total"
        >
        </el-pagination>
        <el-select v-model="inventoryVo.warehouseId" placeholder="请选择仓库">
            <el-option
                    v-for="warehouse in warehouseList"
                    :key="warehouse.id"
                    :label="warehouse.name"
                    :value="warehouse.id">
            </el-option>
        </el-select>
        <el-select v-model="inventoryVo.customerId" placeholder="请选择供应商">
            <el-option
                    v-for="customer in customersList"
                    :key="customer.customerId"
                    :label="customer.customerName"
                    :value="customer.customerId">
            </el-option>
        </el-select>
        <el-select v-model="inventoryVo.outboundType" placeholder="请选择入库类型">
            <el-option
                    v-for="outboundType in outboundTypeList"
                    :key="outboundType.id"
                    :label="outboundType.outboundType"
                    :value="outboundType.id">
            </el-option>
        </el-select>
        <el-date-picker
                v-model="inventoryVo.inventoryTime"
                type="date"
                placeholder="选择日期">
        </el-date-picker>
        <el-input v-model="inventoryVo.outboundNotes" placeholder="请输入备注"></el-input>
        <el-table :data="selectedProducts" style="width: 100%">
            <el-table-column prop="productId" label="商品ID"></el-table-column>
            <el-table-column prop="brand" label="品牌名称"></el-table-column>
            <el-table-column prop="productName" label="商品名称"></el-table-column>
            <el-table-column prop="typeName" label="包装类型名称"></el-table-column>
            <el-table-column prop="weight" label="单位重量"></el-table-column>
            <el-table-column prop="inventoryQuantity" label="入库数量" >
                <template #default="{ row }">
                    <el-input v-model="row.clearQuantity" size="small" placeholder="请输入入库数量"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-button size="small" type="primary" @click="deleteToSelected(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-button size="small" type="primary" @click="submitAll()">提交</el-button>
    </div>
</template>

<script setup>
    import {ref, reactive, computed, onMounted} from 'vue';
    import {selectAllProducts,selectProductName,selectBrandName,submitAllDefective,generateOutbound,getWarehouses} from '@/api/warehouse/invInventory'
    import {getCustomer} from '@/api/sale/customer'
    // 定义数据
    const hidden = ref(false);
    const selectedProducts = ref([]);
    // 定义模态框的显示状态和明细数据
    let productList = ref([]); //商品集合
    const warehouseList = ref([]); // 仓库列表
    const customersList = ref([]);
    const productVo = ref({
        productName:'',
        brand: '',
        typeName:'',
    });
    const inventoryVo = ref({
        warehouseId: '',
        outboundType:'',
        customerId:'',
        outboundNotes:'',
        inventoryTime:'',
    });
    const outboundTypeList = ref([
        {id:0,outboundType:"采购入库"},
        {id:1,outboundType:"退货入库"},
        {id:2,outboundType:"其它"},
    ])
    const brandList = ref([]);
    const productNameList = ref([]);
    const typeNameList = ref([]);

    const page = ref({
        total: 22,
        currentPage: 1,
        pageSize: 10,
    })
    // 定义分页控件的事件处理函数
    function handleSizeChange(newSize) {
        page.value.pageSize = newSize;
        fetchInventory();
    }
    function handleCurrentChange(newPage) {
        page.value.currentPage = newPage;
        fetchInventory();
    }
    function selectInventory() {
        page.value.currentPage = 1;
        fetchInventory();
    }
    // 定义日期格式化方法
    function formatDate(date) {
        return date.toLocaleString('zh-CN', {year: 'numeric', month: '2-digit', day: '2-digit'});
    }
    function fetchWarehouses() {
        getWarehouses().then(response => {
            warehouseList.value = response.warehouses.map(warehouse => ({
                id: warehouse.warehouseId,
                name: warehouse.warehouseName,
            }));
        }).catch(error => {
            console.error('获取仓库列表失败:', error);
            // 这里可以添加错误处理逻辑，例如提示用户
        });
    }
    function fetchGetCustomers() {
        getCustomer().then(response => {
            customersList.value = response.customerList.map(customer => ({
                customerId: customer.customerId,
                customerName: customer.customerName,
            }));
        }).catch(error => {
            console.error('获取仓库列表失败:', error);
            // 这里可以添加错误处理逻辑，例如提示用户
        });
    }
    function fetchProducts() {
        const params = {
            ...productVo.value, // 展开 inventoryVo.value 对象的所有属性
            currentPage: page.value.currentPage, // 当前页码
            pageSize: page.value.pageSize // 每页条数
        };
        selectAllProducts(params).then(response => {
            page.value.total = response.total
            productList.value = response.rows.map(p => ({
                productId: p.productId,
                variantId: p.variantId,
                productName: p.productName,
                brand: p.brand,
                describe: p.describe,
                typeName: p.typeName,
                weight: p.weight,
                number: p.number,
                unitPurchasePrice: p.unitPurchasePrice,
                inventoryQuantity: p.inventoryQuantity,
                clearQuantity: '',
                reason:'',
            }));
            console.log(productList.value)

        }).catch(error => {
            console.error('获取商品列表失败:', error);
            // 错误处理逻辑
        });

    }
    // 添加方法处理添加按钮点击事件
    function addRowToSelected(row) {
        // 查找是否已有相同的商品ID存在于selectedProducts中
        const existingItem = selectedProducts.value.find(item => item.variantId === row.variantId);
        if (!existingItem) {
            selectedProducts.value.push(row);
        }
    }
    function deleteToSelected(row) {
        const index = selectedProducts.value.findIndex(item => item.productId === row.productId);
        if (index !== -1) {
            selectedProducts.value.splice(index, 1);
        }
    }
    function reset() {
        productVo.value = {};
        fetchProducts();
    }
    function submitAll() {
        // 验证所有清理数量是否有值
        const hasEmptyClearQuantity = selectedProducts.value.some(p => !p.clearQuantity);
        if (hasEmptyClearQuantity) {
            alert("请输入出库数量")
            return;
        }
        const defectives = selectedProducts.value.map(p =>({
            variantId:p.variantId,
            handleNumber:p.clearQuantity,
        }))
        const params = {
            ...inventoryVo.value,
            productList:defectives
        }
        generateOutbound(params).then(response =>{
            console.log("生成出库单成功:"+response)
        }).catch(error => {
            console.error('添加商品成功:', error);
            // 错误处理逻辑
        });
    }
    function fetchProductsName(){
        selectProductName().then(response => {
            productNameList.value = response.productNameList;
        }).catch(error => {
            console.error('获取商品名失败:', error);
            // 错误处理逻辑
        });
    }
    function fetchBrand(){
        selectBrandName().then(response => {
            brandList.value = response.brandList; // 直接赋值字符串数组
        }).catch(error => {
            console.error('获取品牌失败:', error);
            // 错误处理逻辑
        });
    }

    // 定义加载数据的方法
    function loadOptions() {
        fetchWarehouses();
        fetchProducts();
        fetchProductsName();
        fetchBrand();
        fetchGetCustomers();
    }

    onMounted(() => {
        // 初始化逻辑
        loadOptions();
        //fetchInventory();
    });
</script>

<style scoped>

</style>